<template>
  <el-dialog class="pick-dialog" title="赔付详情" :visible.sync="dialogVisible" :close-on-click-modal="false" width="1000px">
    <div class="form-box" v-loading="loading">

      <div class="sale-info flex fbt">
        <div>
          <el-descriptions :labelStyle="{
            width:'100px'

          }" title="商品信息" labelClassName="label-txt" border :column='1'>
            <el-descriptions-item label="游戏名称">{{ saleOrder.gameName }}</el-descriptions-item>
            <el-descriptions-item label="游戏账号">{{ saleOrder.accountNumber }}</el-descriptions-item>
            <el-descriptions-item label="区服">{{ saleOrder.qufu }}</el-descriptions-item>
            <el-descriptions-item label="商品编号">{{ saleOrder.goodsId }}</el-descriptions-item>
            <!-- <el-descriptions-item label="平台售价">{{ saleOrder.platformAmount }}</el-descriptions-item> -->
          </el-descriptions>
        </div>
        <div>
          <el-descriptions :labelStyle="{
            width:'100px'

          }" title="订单信息" labelClassName="label-txt" border :column='1'>
            <el-descriptions-item label="买家名称">{{ saleOrder.saleChannel }}</el-descriptions-item>
            <el-descriptions-item label="卖家名称">{{ saleOrder.supplyTenantName }}</el-descriptions-item>
            <el-descriptions-item label="商品价格">{{ saleOrder.platformAmount }}</el-descriptions-item>
            <!-- <el-descriptions-item label="优惠后金额" >{{ saleOrder.saleAmount }}</el-descriptions-item>
              <el-descriptions-item label="折扣比例">{{ !saleOrder.saleDiscount||saleOrder.saleDiscount=='0.0'?10:saleOrder.saleDiscount }}</el-descriptions-item> -->
            <el-descriptions-item label="实付金额">{{ saleOrder.actualAmount }}</el-descriptions-item>
            <el-descriptions-item label="支付状态">{{commonMaps.buyerPayState[saleOrder.salePay]  }}</el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
      <div style="margin-top:15px">
        <el-descriptions :labelStyle="{
            width:'110px'
          }" title="赔付申请信息" labelClassName="label-txt" border :column='3'>
          <el-descriptions-item label="赔付类型">无货赔付</el-descriptions-item>
          <el-descriptions-item label="赔付金额">{{info.sqAmount}}</el-descriptions-item>
          <el-descriptions-item label="申请描述" :span="3">{{ info.sqRemark }}</el-descriptions-item>
          <el-descriptions-item label="图片" :span="3">
            <div v-if="sqImgs&&sqImgs.length">
              <el-image style="width:80px;height:80px; margin-right:10px;margin-bottom:10px" :preview-src-list="sqImgs" preview v-for="(img,i) in sqImgs" :key="i" :src="img"></el-image>

            </div>
          </el-descriptions-item>
          <el-descriptions-item v-if="flag=='kefu'" label="交易群聊" :span="3">
            <el-button type="primary" @click="openHistoryMsg">查看群聊记录</el-button>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <div style="margin-top:15px" v-if="flag=='kefu'">
        <el-descriptions :labelStyle="{
            width:'110px'
          }" title="赔付处理信息" labelClassName="label-txt" border :column='3'>
          <el-descriptions-item label="赔付描述" :span="3">{{ info.pfRemark }}</el-descriptions-item>
          <el-descriptions-item label="图片" :span="3">
            <div v-if="pfImg&&pfImg.length">
              <el-image style="width:80px;height:80px; margin-right:10px;margin-bottom:10px" :preview-src-list="pfImg" preview v-for="(img,i) in pfImg" :key="i" :src="img"></el-image>
            </div>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <el-divider content-position="left">赔付补充资料</el-divider>
      <el-form :model="ruleForm" ref="ruleForm" label-width="auto" :rules="rules" class="demo-ruleForm">
        <el-form-item v-if="flag=='kefu'" label="申请介入原因:" prop="">
          <b style="color:red">{{info.jrRemark}}</b>
        </el-form-item>
        <el-form-item v-if="flag=='seller'" label="赔付金额:" prop="sjAmount">
          <b style="color:red">{{ruleForm.sjAmount}}元</b>
        </el-form-item>
        <el-form-item v-if="flag=='kefu'" label="赔付金额:" prop="sjAmount">
          <el-input style="width: 250px" v-model="ruleForm.sjAmount" type="text" placeholder="请输入赔付金额"></el-input>
        </el-form-item>
        <el-form-item v-if="flag=='seller'" label="处理结果:" prop="pfRemark">
          <el-input style="width: 600px" v-model="ruleForm.pfRemark" type="textarea" rows="5" placeholder="请输入赔付处理结果描述..."></el-input>
        </el-form-item>
        <el-form-item v-if="flag=='kefu'" label="处理结果:" prop="kfRemark">
          <el-input style="width: 600px" v-model="ruleForm.kfRemark" type="textarea" rows="5" placeholder="请输入赔付处理结果描述..."></el-input>
        </el-form-item>
        <el-form-item label="图片:" prop="">
          <el-upload :action="uploadImgUrl" list-type="picture-card" :file-list="imgShowList0" :multiple="true" :on-preview="handlePictureCardPreview" :on-success="handleUploadSuccess0" :on-remove="handleRemove0" :limit="9" :headers="headers">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
      </el-form>

      <div class="center">
        <el-button @click="submitForm('ruleForm', 'refuse')">拒绝赔付</el-button>
        <el-button type="primary" @click="submitForm('ruleForm', 'agree')" :loading="loading">同意赔付</el-button>
      </div>
    </div>
    <MsgHistroy :showDialog="showDialog" @close="guanbi" :sessionId="toGroups" />
  </el-dialog>
</template>

<script>
import orderApi from "@/api/pickUp/order.js";
import { getToken } from "@/utils/auth";
import {
  claimRecordChangeSeller,
  claimRecordkfchange,
  getDetailclaimRecord,
  groupGetById,
} from "../../../../api/peifu";

import MsgHistroy from "@/views/IMmsg/msgHistory/index.vue";
export default {
  name: "afterOrderDone",
  components: { MsgHistroy },
  data() {
    var priceRule = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入赔付金额"));
      } else if (!this.priceReg.test(value)) {
        callback(new Error("请输入正确的金额"));
      } else {
        callback();
      }
    };
    return {
      dialogVisible: false,
      loading: false,
      info: "",
      infoArr: [],
      userInfo: {}, //当前登录人信息
      afterReasons: [],
      sqImgs: [],
      pfImg: [],
      ruleForm: {
        id: "",
        pfRemark: "",
        pfImg: "",
        pfState: "",
        kfState: "",
        kfRemark: "",
        kfImg: "",
        sjAmount: "",
      },
      rules: {
        sjAmount: [
          { required: true, message: "请输入赔付金额", trigger: "blur" },
          { validator: priceRule, trigger: "blur" },
        ],
      },
      // 上传相关
      uploadImgUrl: "",
      imgShowList0: [],
      newImages0: [],
      imgFileList0: [],
      saleOrder: {},
      weiguiList: [],
      violationRulesIds: [],
      headers: {},
      sumAmount: 0, //已经售后的金额
      flag: "", //卖家处理或者客服处理

      showDialog: false, //聊天记录弹出
      toGroups: "",
    };
  },
  created() {
    this.uploadImgUrl = process.env.VUE_APP_BASE_API + "/upload/image";
    this.headers = {
      Authorization: "Bearer " + getToken(),
    };
  },
  methods: {
    open(info, flag) {
      this.flag = flag;
      this.ruleForm = {
        id: "",
        pfRemark: "",
        pfImg: "",
        pfState: "",
        kfState: "",
        kfRemark: "",
        kfImg: "",
        sjAmount: "",
      };
      this.ruleForm.id = info.id;
      this.getPeifuOrderInfo();
      this.dialogVisible = true;
    },
    // 客服查看群聊记录
    async openHistoryMsg() {
      if (!this.saleOrder.toGroup) {
        if (this.saleOrder.msgGroupInfoId) {
          try {
            const res = await groupGetById({
              id: this.saleOrder.msgGroupInfoId,
            });
            this.toGroups =res.data.toGroup
          } catch (err) {
            return this.$message.error("该订单没有关联群聊！");
          }
        } else {
          return this.$message.error("该订单没有关联群聊！");
        }
      } else {
        this.toGroups = this.saleOrder.toGroup;
      }
      this.showDialog = true;
    },
    //guanbi 群聊记录
    guanbi() {
      this.showDialog = false;
    },

    // 获取售后订单详情
    getPeifuOrderInfo() {
      this.loading = true;
      this.sqImgs = [];
      getDetailclaimRecord(this.ruleForm.id).then((res) => {
        this.info = res.data;
        this.ruleForm.sjAmount = this.info.sjAmount;
        if (this.info.sqImg) {
          let imgs = [];
          let arr = JSON.parse(this.info.sqImg);
          arr.forEach((r) => {
            imgs.push(r.url);
          });
          this.sqImgs = imgs;
        }
        if (this.info.pfImg) {
          let imgs = [];
          let arr = JSON.parse(this.info.pfImg);
          arr.forEach((r) => {
            imgs.push(r.url);
          });
          this.pfImg = imgs;
        }
        this.getSaleOrderInfo();
      });
    },
    // 获取销售订单详情
    getSaleOrderInfo() {
      let obj = {
        id: this.info.sourceId,
        dataType: "",
        type: "",
      };
      if (this.flag == "seller") {
        // 是卖家  查询销售订单
        obj = {
          id: this.info.sourceId,
          dataType: "sell",
          type: 1,
        };
      }
      if (this.flag == "kefu") {
        // 是客服
        obj = {
          id: this.info.sourceId,
          dataType: "all",
          type: "",
        };
      }
      orderApi.orderPayStatusHandle(obj).then((res) => {
        this.saleOrder = res.data;
        this.loading = false;
      });
    },
    // 点击提交按钮
    submitForm(formName, type) {
      this.$confirm(
        `确认${type == "agree" ? "同意" : "拒绝"}该赔付申请吗？`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          if (type == "refuse") {
            this.submitFormSure(type);
          } else {
            this.$refs[formName].validate((valid) => {
              if (valid) {
                // 判断金额是否超过订单实付

                this.submitFormSure(type);
              } else {
                //console.log("error submit!!");
                return false;
              }
            });
          }
        })
        .catch(() => {});
    },
    // 提交售后处理
    async submitFormSure(type) {
      this.loading = true;
      // 组装图片附件
      // 拼接新上传的图片
      let ziliao = [];
      if (this["newImages0"] && this["newImages0"].length) {
        let newArr = [];
        this["newImages0"].forEach((img) => {
          newArr.push({
            name: img.name,
            url: img.response.data.filePath,
          });
        });
        ziliao = this["imgFileList0"].concat(newArr);
      } else {
        ziliao = this["imgFileList0"];
      }
      if (this.flag == "seller") {
        // 卖家处理
        this.ruleForm.pfImg = JSON.stringify(ziliao);
        if (type == "refuse") {
          this.ruleForm.pfState = 3;
        } else if (type == "agree") {
          this.ruleForm.pfState = 2;
        }
      } else if (this.flag == "kefu") {
        // 客服处理
        this.ruleForm.kfImg = JSON.stringify(ziliao);
        if (type == "refuse") {
          this.ruleForm.kfState = 3;
        } else if (type == "agree") {
          this.ruleForm.kfState = 2;
        }
      }
      let res;
      try {
        if (this.flag == "seller") {
          // claimRecordChangeSeller,claimRecordkfchange
          res = await claimRecordChangeSeller(this.ruleForm);
        } else if (this.flag == "kefu") {
          res = await claimRecordkfchange(this.ruleForm);
        }
      } catch (error) {
        this.loading = false;
      }
      this.loading = false;
      if (res.code == 200) {
        this.$message.success("赔付处理成功");
        this.$parent.getList();
        this.close();
      }
    },

    // 上传图片相关
    // 图片预览
    handlePictureCardPreview(file) {
      this.$viewerApi({
        images: [file.url],
      });
    },
    uploadNumber(file, fileList) {
      //限制图片数量
      this.$modal.msgError("最多只能上传9张图片");
    },
    // 图片上传成功
    handleUploadSuccess0(res, file, fileList) {
      if (res.code == 200) {
        // 取得新上传的文件
        this.newImages0 = fileList.filter((t) => {
          return t.url.indexOf("blob:") > -1;
        });
      }
    },
    // 图片删除
    handleRemove0(response) {
      const that = this;
      // 1.获取将要删除图片的临时路径
      const filePath = response.url;
      // 2.找到图片对应的索引值
      this.imgFileList0.forEach(function (element, key) {
        if (element.url === filePath) {
          that.imgFileList0.splice(key, 1); //回显的图片
        }
      });
      this.newImages0.forEach(function (element, key) {
        if (element.url === filePath) {
          that.newImages0.splice(key, 1); //新上传的图片
        }
      });
    },
    close(formName) {
      this.dialogVisible = false;
    },
  },
};
</script>
<style scoped lang="scss">
.order-info {
  box-sizing: border-box;
  // height: 50px;
  background: #eee;
  padding: 15px;
  margin-bottom: 10px;
  flex-wrap: wrap;
  line-height: 26px;

  > span {
    margin-right: 20px;
  }
}
.form-box {
  .sale-info {
    width: 100%;
    align-content: space-between;
    margin-top: 20px;
    > div {
      width: 50%;
      margin-right: 15px;
    }
  }
}

.zdy-des {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 4;
  margin: 6px 0;
}

.demo-ruleForm {
  padding-right: 20px;
}

.center {
  text-align: right;
}

.pick-dialog >>> .el-input--medium input {
  text-align: left;
}
</style>
